import React, { Component } from 'react';
import './index.less';
import { Spin, message, Modal } from 'antd';
import { post } from '@/utils/requestUtil';
import { commonQueryByCode, getDocumentById } from '@/service/document/documentService';
import ImagePreviewMasked from '../ImagePreviewMasked';
import { DeleteOutlined } from '@ant-design/icons';
import AuthImg from '../AuthImg/AuthImg';

export default class PhotoAlbums extends Component {
    constructor(props) {
        super(props);
        this.fileInputRef = null;
        this.state = {
            albumsId: null,
            albumsTopic: null,
            albumsDes: null,
            loading: true,
            fileInfoList: [],
            imagePreviewVisul: false,
            currentPreviewSrc: null
        }
    }

    async componentDidMount() {
        if (this.props.albumsId) {
            let albumsTopic = null;
            let albumsDes = null;
            const response = await getDocumentById({
                id: this.props.albumsId,
                serviceName: 'blog',
                collectionName: 'customer_private_photo_albums'
            })
            if (response && response.code === 200) {
                albumsTopic = response.data.content.topic;
                albumsDes = response.data.content.description;
            }
            const fileInfoList = await this.getFileInfoList();
            this.setState({
                albumsId: this.props.albumsId,
                albumsTopic,
                albumsDes,
                fileInfoList,
                loading: false
            });
        }
    }

    getFileInfoList = async () => {
        let fileInfoList = [];
        const response = await commonQueryByCode({
            commandCode: 'searchPhotosByAlbumsId',
            kvMap: {
                albumsId: this.props.albumsId
            }
        });
        if (response && response.code === 200) {
            fileInfoList = response.data.documents.map(item => item.content);
        }
        return fileInfoList;
    }

    handleUploadClick = () => {
        this.fileInputRef.click();
    };

    handleFileChange = async (event) => {
        const file = event.target.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('file', file);
            const response = await post(`/file/upload/albums/${this.state.albumsId}`, {
                body: formData
            }, { notSetContentType: true });
            if (response && response.code === 200) {
                message.success('上传成功');
                const fileInfoList = await this.getFileInfoList();
                this.setState({ fileInfoList });
            } else {
                message.error('上传失败');
            }
            event.target.value = '';
        }
    };

    openPreview = (src) => {
        this.setState({
            imagePreviewVisul: true,
            currentPreviewSrc: src
        });
    }

    closePreview = () => {
        this.setState({
            imagePreviewVisul: false
        });
    }

    deletePhoto = async (fileId) => {
        Modal.confirm({
            title: '确定要删除这张照片吗？',
            content: '删除后不可恢复',
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
                const response = await post(`/blog/albums/delete/photo/${this.state.albumsId}`, {
                    body: JSON.stringify([fileId])
                });
                if (response && response.code === 200) {
                    message.success('删除成功');
                    const fileInfoList = await this.getFileInfoList();
                    this.setState({ fileInfoList });
                }
            }
        });
    }

    render() {
        if (this.state.loading) return <Spin />
        const imageArray = this.state.fileInfoList.map(item => { return { src: item.filePath } });
        return (
            <>
                <div className="photo-albums-main">
                    <div className="photo-albums-title">
                        <span className='photo-albums-title-main'>{this.state.albumsTopic}</span>
                        <span className='photo-albums-title-description'>{this.state.albumsDes}</span>
                    </div>
                    <div className="photo-albums-content">
                        <div className="photo-albums-list">
                            <div className="photo-albums-upload" onClick={this.handleUploadClick}>
                                <input
                                    type="file"
                                    ref={ref => { this.fileInputRef = ref }}
                                    onChange={this.handleFileChange}
                                    style={{ display: 'none' }}
                                />
                                <span>点击上传图片</span>
                            </div>
                            {
                                this.state.fileInfoList.map((item) => {
                                    return (
                                        <div className="photo-albums-item" key={item.fileId}>
                                            <div className="photo-albums-item-img">
                                                <div className='photo-albums-item-img-utils'>
                                                    <DeleteOutlined onClick={async () => {
                                                        this.deletePhoto(item.fileId);
                                                    }} />
                                                </div>
                                                <AuthImg
                                                    authSrc={item.filePath}
                                                    alt=""
                                                    onClick={() => this.openPreview(item.filePath)}
                                                />
                                            </div>
                                            <div className="photo-albums-item-name">
                                                {item.fileName}
                                            </div>
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>
                </div>
                <ImagePreviewMasked
                    visual={this.state.imagePreviewVisul}
                    onCancel={this.closePreview}
                    src={this.state.currentPreviewSrc}
                    imageArray={imageArray}
                >
                </ImagePreviewMasked>
            </>
        );
    }
}